package com.JackTang.fruit.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Jack Tang
 * @description
 * @create 2023-09-06 10:37
 */
public class JDBCUtilsV2 {
    private static DataSource dataSource = null; //连接池对象

    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    static {
        //初始化连接池对象
        Properties props = new Properties();
        InputStream ips = JDBCUtilsV2.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            props.load(ips);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * 对外提供连接方法
     */
    public static Connection getConnection() throws SQLException {
        //线程本地变量中是否存在
        Connection conn = tl.get();

        //第一次没有
        if (conn == null){
            //线程本地变量没有，连接池获取
            conn = dataSource.getConnection();
            tl.set(conn);
        }

        return conn;
    }

    //回收
    public static void freeConnection() throws SQLException {

        Connection conn = tl.get();
        if (conn != null) {
            tl.remove(); //清空线程本地变量数据
            conn.setAutoCommit(true); //事务状态回归
            conn.close(); //连接池的连接，调用close就是回收！
        }
    }
}